import itertools

from framework.common import util
import copy
from framework.common.pt_logger import logger


class Result(object):
    def __init__(self):
        self.source_url = ""
        self.metadata = dict()
        self.items = dict()
        self.tags = dict()

    @classmethod
    def from_json(cls, data):
        if data is None:
            return None
        else:
            obj = cls()
            obj.source_url = data.get("source_url")
            obj.metadata = data.get("metadata")
            obj.items = data.get("items")
            obj.tags = data.get("tags")
            return obj

    def __repr__(self):
        return "source_url:%s, metadata:%s, items:%s, tags:%s" % (self.source_url, self.metadata, self.items, self.tags)

    @classmethod
    def from_task(cls, task, **kwargs):
        return cls.create(task.url, task.metadata, task.tags, **kwargs)

    @classmethod
    def create(cls, source_url, metadata=None, tags=None, **kwargs):
        r = cls()
        r.source_url = source_url
        if metadata:
            r.metadata = {**r.metadata, **metadata}
        # r.result_types = set(itertools.chain(r.result_types, result_types))
        # r.result_types.add(result_types)
        r.items = dict()
        r.put_tags(tags)
        for k, v in kwargs.items():
            r.items[k] = v
        return r

    def copy_tags(self, tags=None):
        if tags is None:
            tags = dict()
        return {**copy.deepcopy(self.tags), **tags}

    def get_item(self, key):
        if key in self.items:
            return self.items[key]
        else:
            return None

    # def get_item(self, key, merge_str=False):
    #     if not merge_str:
    #         return self.items[key]
    #
    #     item = self.items[key]
    #     if isinstance(item, list):
    #         lst = [str(elem).strip() for elem in item]
    #         return "".join(lst).strip()
    #     else:
    #         return item

    def put_tags(self, tags):
        if tags is None:
            return
        if isinstance(tags, dict):
            for k, v in tags.items():
                self.tags[k] = v
        else:
            logger.error("only support put dict() as tags...")

    def put_tag(self, key, value):
        self.tags[key] = value

    def get_tag(self, key):
        if key in self.tags:
            return self.tags[key]
        else:
            return None
